from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from core.models.course_period import CoursePeriod
from core.forms.course_period_form import CoursePeriodForm
import json
import logging

# 配置日志
logger = logging.getLogger(__name__)


def format_time(time_obj):
    """格式化时间为HH:MM格式"""
    return time_obj.strftime('%H:%M') if time_obj else None


def serialize_period(period):
    """序列化课程时间段对象"""
    return {
        'id': period.id,
        'name': period.name,
        'start_time': format_time(period.start_time),
        'duration': period.duration,
        'end_time': format_time(period.end_time)
    }


def handle_exception(e, default_message='操作失败'):
    """统一异常处理"""
    logger.error(f'操作异常: {str(e)}')
    if isinstance(e, CoursePeriod.DoesNotExist):
        return JsonResponse({'success': False, 'error': '课程时间段不存在'})
    return JsonResponse({'success': False, 'error': default_message})


@csrf_exempt
@require_http_methods(['GET'])
def get_course_period(request, pk):
    """获取单个课程时间段"""
    try:
        period = CoursePeriod.objects.get(pk=pk)
        return JsonResponse({'success': True, 'data': serialize_period(period)})
    except Exception as e:
        return handle_exception(e)


@csrf_exempt
@require_http_methods(['POST'])
def create_course_period(request):
    """创建课程时间段"""
    try:
        data = json.loads(request.body)
        form = CoursePeriodForm(data)
        if form.is_valid():
            period = form.save()
            return JsonResponse({
                'success': True,
                'data': serialize_period(period)
            })
        else:
            return JsonResponse({'success': False, 'error': form.errors})
    except Exception as e:
        return handle_exception(e, '创建课程时间段失败')


@csrf_exempt
@require_http_methods(['PUT'])
def update_course_period(request, pk):
    """更新课程时间段"""
    try:
        period = CoursePeriod.objects.get(pk=pk)
        data = json.loads(request.body)
        form = CoursePeriodForm(data, instance=period)
        if form.is_valid():
            period = form.save()
            return JsonResponse({
                'success': True,
                'data': serialize_period(period)
            })
        else:
            return JsonResponse({'success': False, 'error': form.errors})
    except Exception as e:
        return handle_exception(e, '更新课程时间段失败')


@csrf_exempt
@require_http_methods(['DELETE'])
def delete_course_period(request, pk):
    """删除课程时间段"""
    try:
        period = CoursePeriod.objects.get(pk=pk)
        period.delete()
        return JsonResponse({'success': True, 'message': '删除成功'})
    except Exception as e:
        return handle_exception(e, '删除课程时间段失败')